from qgis.gui import QgsMapToolEmitPoint, QgsMapTool
from qgis.core import QgsPointXY
from qgis.PyQt.QtCore import pyqtSignal, Qt


class PickCoordinate(QgsMapToolEmitPoint):
    """
    参考：https://gis.stackexchange.com/questions/108044/getting-coordinates-by-clicking-on-qgis-canvas-with-pyqgis
    """
    mouseClicked = pyqtSignal(QgsPointXY)

    def __init__(self, canvas):
        super(PickCoordinate, self).__init__(canvas)
        self.mapCanvas = canvas

    def canvasPressEvent(self, e):
        if e.button() == Qt.LeftButton:
            pt = QgsPointXY(self.mapCanvas.getCoordinateTransform().toMapCoordinates(e.x(), e.y()))
            self.mouseClicked.emit(pt)
